# -*- coding: utf-8 -*-

"""
@author: Rwing
@software: PyCharm
@file: comm.py
@time: 2021/12/2 17:32
"""
import uuid
from threading import Thread

from django.core.cache import cache
from django.template.loader import render_to_string
from django.core.mail import EmailMessage

from App.views_constant import SERVER_HOST, SERVER_PORT


def create_token(request, user_id, is_login=True, timeout: list = None):
    """
    处理注册和登录的token
    :param request:
    :param user_id: 用户表对应的唯一id
    :param is_login: 是否登录模式，默认为True，主要区分注册不会设置session中的token值
    :param timeout: 过期时间，默认是列表格式，[s, m, h]
    :return: 用户生成的唯一token值
    """
    if timeout is None:
        timeout = [60, 60, 24]
    token = uuid.uuid4().hex
    cache.set(token, user_id, timeout=timeout[0] * timeout[1] * timeout[2])
    if is_login:
        request.session["token"] = token
    return token


def async_process(func):
    """实现异步处理事件"""

    def wrapper(*args, **kwargs):
        thr = Thread(target=func, args=args, kwargs=kwargs)
        thr.start()

    return wrapper


def process_food_type(food_type_child_name: str) -> list:
    """
    处理子分类信息
    :param food_type_child_name: 未处理过的子分类字符串，格式是：全部分类:0#进口水果:103534#国产水果:103533
    :return: 格式为：[['全部分类', '0'], ['进口水果', '103534'], ['国产水果', '103533']]
    """
    food_type_child_names_list = food_type_child_name.split("#")
    return [food_type_child_name.split(
        ":") for food_type_child_name in food_type_child_names_list]


@async_process
def send_mail_active(username, token, email, file_path=None):
    """
    注册成功发送激活邮件到注册用户邮箱中
    :param username: 注册的用户名
    :param token: 激活的url，需要经过处理
    :param email: 注册的邮箱
    :param file_path: 邮件中需要附带的文件，默认为空
    :return:
    """
    recipient_list = [email]  # 收货地址，可以加入多个
    data = {
        'username': username,
        'active_url': "http://{}:{}/app/active/?u_token={}".format(SERVER_HOST, SERVER_PORT, token),
    }
    mail = EmailMessage(
        subject="AXF {} Activate".format(username),  # 邮件标题
        body=render_to_string('user/email.html', data),  # 将html文件和data渲染成浏览器认的内容
        from_email='925133387@qq.com',  # 从哪里发出，即发送邮箱
        to=recipient_list
    )
    mail.content_subtype = "html"  # 指定内容是html
    if file_path:
        mail.attach_file(file_path)
    mail.send()


if __name__ == '__main__':
    send_mail_active("Rwing", "https://www.baidu.com", "chenwenwei@shiyue.com", )
    # print(process_food_type("全部分类:0#进口水果:103534#国产水果:103533"))
